package com.framework.main.sys.user.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.struts2.ServletActionContext;

import com.framework.base.constant.ActionConstants;
import com.framework.base.constant.WebConstants;
import com.framework.base.struts.BaseAction;
import com.framework.base.struts.BaseVo;
import com.framework.base.struts.Result;
import com.framework.base.util.StringUtil;
import com.framework.base.util.Struts2Utils;
import com.framework.base.util.SysConfUtil;
import com.framework.main.sys.user.domain.UserOrRoleVo;
import com.framework.main.sys.user.domain.UserVo;
import com.framework.main.sys.user.service.UserService;
import com.oa.omt.recievemail.service.RecievemailService;
import com.opensymphony.xwork2.ActionContext;

/**
 * @Copyright @ 2011 All right reserved
 * @version 创建时间：Created on 2011-5-21
 * @author 作者：Create by HYH
 * @Email: 517372264@qq.com
 * @description 用于管理用户数据请求
 * 
 */
@SuppressWarnings("serial")
public class UserAction extends BaseAction {
	private UserOrRoleVo uorv;
	private UserService userService;
	private String message;


	public UserAction() {
		getLogger().info("useraction init");
	}

	private File userFile;
	public File getUserFile() {
		return userFile;
	}

	public void setUserFile(File userFile) {
		this.userFile = userFile;
	}
	
	private String email;
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
	private RecievemailService recievemailService;
	public RecievemailService getRecievemailService() {
		return recievemailService;
	}
	public void setRecievemailService(RecievemailService recievemailService) {
		this.recievemailService = recievemailService;
	}

	/**
	 * 用户登录
	 * 
	 * @param cfg
	 * @return
	 * @throws Exception
	 */
	public String login() throws Exception {
		String language=(String) ActionContext.getContext().getApplication().get("language");
		if (StringUtil.isNullorEmpty(language)||"zh_CN".equals(language)) {
			this.getLocale().setDefault(Locale.SIMPLIFIED_CHINESE);			 
		}else {
			this.getLocale().setDefault(Locale.US);
		}
		Result Result = this.getUserService().toLogin((UserVo) this.getVo());
		if (Result.getResultMap().get(WebConstants.CURRENTUSER) == null) {

		} else {
		}
		setMessage((String) Result.getResultMap().get("loginInfo"));
		if(null!=Struts2Utils.getCurrentUser()){
			email = recievemailService.getIsRead(Struts2Utils.getCurrentUser().getIdf());
		}
		return Result.getForwardName();
	}


	/**
	 * 获得当前用户的权限	 * 
	 * @param cfg
	 * @return
	 * @throws Exception
	 */

	public String toDistribute() throws Exception {
		String pk = Struts2Utils.getRequest().getParameter("fid");
		Result result = this.getUserService().toDistribute(pk);
		Struts2Utils.forwardParams(result.getResultMap());
		this.setVo(result.getVo());
		return result.getForwardName();
	}

	/**
	 * 保存权限
	 * 
	 * @param cfg
	 * @return
	 * @throws Exception
	 */
	public String doDistribute() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String pk = Struts2Utils.getRequest().getParameter("fid");
		String[] value = Struts2Utils.getRequest().getParameterValues(
				"moduAndOper");
		String in = Struts2Utils.getRequest().getParameter(
				"sendObject_0_UsersId");
		String out = Struts2Utils.getRequest().getParameter(
				"sendObject_1_UsersId");// sendObject_1_UsersId
		String defin = Struts2Utils.getRequest().getParameter(
				"chksendObject_0_UsersId");// chksendObject_0_UsersId
		String defout = Struts2Utils.getRequest().getParameter(
				"chksendObject_1_UsersId");// chksendObject_1_UsersId
		map.put("pk", pk);
		map.put("value", value);
		map.put("in", in);
		map.put("out", out);
		map.put("defin", defin);
		map.put("defout", defout);
		Result result = this.getUserService().doDistribute(map);
		Struts2Utils.forwardParams(result.getResultMap());
		return result.getForwardName();
	}

	/**
	 * 显示人员选择数据
	 * 
	 * @param cfg
	 * @return
	 * @throws Exception
	 */
	public String toselectUser() throws Exception {
		String pk = Struts2Utils.getRequest().getParameter("fid");
		String type = Struts2Utils.getRequest().getParameter("type");
		if (pk == null || "".equals(pk)) {
			pk = (String) Struts2Utils.getRequest().getAttribute("pk");
		}
		Result result = this.getUserService().toselectUser(pk, type);
		Struts2Utils.forwardParams(result.getResultMap());
		return result.getForwardName();
	}

	@Override
	public String toList() throws Exception {
		/*
		 * changeState 更改用户的状态
		 */
		String stateAction = StringUtil.nullToEmpty(ServletActionContext
				.getRequest().getParameter("stateAction"));
		String selectidf = StringUtil.nullToEmpty(ServletActionContext
				.getRequest().getParameter("selectidf"));
		String stateValue = StringUtil.nullToEmpty(ServletActionContext
				.getRequest().getParameter("stateValue"));

		if ("changeState".equals(stateAction)) {
			Map<String, Object> mapResult = userService.doChangeState(
					selectidf, stateValue);
			Struts2Utils.forwardParams(mapResult);
		}
		return super.toList();
	}
	
	/**
	 * 根据班级id查找学生信息
	 * @param cfg
	 * @return
	 * @throws Exception
	 */
	public String ByIdLoadUsers()throws Exception{
		String deptId = Struts2Utils.getRequest().getParameter("deptId");
		/*
		 * changeState 更改用户的状态

		 */
		String stateAction = StringUtil.nullToEmpty(ServletActionContext
				.getRequest().getParameter("stateAction"));
		String selectidf = StringUtil.nullToEmpty(ServletActionContext
				.getRequest().getParameter("selectidf"));
		String stateValue = StringUtil.nullToEmpty(ServletActionContext
				.getRequest().getParameter("stateValue"));

		if ("changeState".equals(stateAction)) {
			Map<String, Object> mapResult = userService.doChangeState(
					selectidf, stateValue);
			Struts2Utils.forwardParams(mapResult);
		}
		setQueryMap(Struts2Utils.initQueryMap(getParamsUrl(), getQueryMap()));
		HashMap<String,Object> paramsMap=(HashMap<String, Object>) Struts2Utils.getParameterMap(getQueryMap(),this.getVo());
		Result result = ((UserService)this.getBaseService()).toListb(paramsMap);
		setPage(result.getPage());
		return result.getForwardName();
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/**
	 * 个人办公 -->> 个人信息修改
	 * 
	 * 
	 * @return
	 * @throws Exception
	 */
	public String toUpdate1() throws Exception {
		UserVo user = Struts2Utils.getCurrentUser();
		Result Result = this.getBaseService().getById(user.getIdf());
		this.setVo(Result.getVo());
		return Result.getForwardName();
	}
	/**
	 * 用于跳转到top页面
	 * @return
	 * @throws Exception
	 */
	public String toTop() throws Exception {
		return ActionConstants.SUCCESS;
	}
	/**
	 * 个人办公 -->> 个人信息修改
	 * 
	 * 
	 * @return
	 * @throws Exception
	 */
	public String doUpdate1() throws Exception {
		this.getBaseService().doUpdate(this.getVo());
		return this.toUpdate1();
	}

	// 退出系统
	public String userLoginOut() throws Exception {
		Struts2Utils.getResponse().setHeader("Pragma", "No-cache");
		Struts2Utils.getResponse().setHeader("Cache-Control", "no-cache"); // 强制缓存从服务器上获取新的页面
		Struts2Utils.getResponse().setHeader("Cache-Control", "no-store"); // 在任何环境下缓存不保存任何页面
		Struts2Utils.getResponse().setDateHeader("Expires", 0);
		Struts2Utils.getSession().invalidate();
	
		return ActionConstants.RELOAD;
	}

	public String toLogin() throws Exception {
		return ActionConstants.SUCCESS;
	}

	public String updatePass() throws Exception {
		String oldPass = Struts2Utils.getParameter("oldPass");
		String newpassword = Struts2Utils.getParameter("newpassword");
		UserService userService = (UserService) this.getBaseService();
		PrintWriter write = Struts2Utils.getResponse().getWriter();
		if (userService.checkPass(oldPass) == false) {
			write.write("0");
		} else {
			write.write(userService.updatePass(newpassword));
		}
		write.flush();
		write.close();
		return ActionConstants.SUCCESS;
	}
	
	public String toUpdatePass() throws Exception {
		return ActionConstants.SUCCESS;
	}
	
	/**
	 * 取得用户全部菜单
	 * @return
	 * @throws Exception
	 */
	public String getMenu() throws Exception{
		UserService userService = (UserService) this.getBaseService();
		String userName = SysConfUtil.getConfValue("userName");
		String password = SysConfUtil.getConfValue("password");
		UserVo userVo = Struts2Utils.getCurrentUser();
		boolean flag = false;
		if(userName.indexOf(userVo.getUserNamef())>-1 && password.indexOf(userVo.getUserPwdf())>-1){
			flag = true;
		}
		Struts2Utils.getSession().setAttribute("control", flag);
		userService.getMenu();
		return SUCCESS;
	}

	/**
	 * @return the message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message
	 *            the message to set
	 */
	public void setMessage(String message) {
		this.message = message;
	}
	public String toInsertUsers() throws Exception {
		return SUCCESS;
	}
	public String toInsertUsersb() throws Exception {
		Result result=userService.toRoleList("");
		List<BaseVo> roles=(List<BaseVo>)result.getResultMap().get("roleList");
		Struts2Utils.getRequest().setAttribute("roleList", roles);
		return result.getForwardName();
	}
	
	public String doInsertb() throws Exception {
		List<BaseVo> users=new ArrayList<BaseVo>();
		UserVo user=(UserVo)getVo();
		user.setCreateidf(Struts2Utils.getCurrentUser().getIdf());
		user.setUserType("3");
		users.add(user);
		getLogger().info("getDeptidf======"+user.getDeptidf());
		return ((UserService)this.getBaseService()).doInsertUsers(users,user.getDeptidf());
	}
	
	public String doInsertUsers() throws Exception {
		//List failList = new ArrayList();
		//int count=0;
		List<BaseVo> users=Read(userFile.getPath());
		//((UserService)this.getBaseService()).doInsertUsers(users,Struts2Utils.getParameter("deptId"));
		//Struts2Utils.getRequest().setAttribute("successCount", count);
		//Struts2Utils.getRequest().setAttribute("errorCount", failList.size());
		//Struts2Utils.getSession().setAttribute("failList", failList);
		return ((UserService)this.getBaseService()).doInsertUsers(users,getQueryMap().get("deptId").toString());
	}
	
	public String doInsertUsersb() throws Exception {
		List<BaseVo> users=new ArrayList<BaseVo>();
		
		for(int i=uorv.getIdnumbegin();i<=uorv.getIdnumend();i+=uorv.getIdnumstep()){
			UserVo user = new UserVo();
			
			user.setCreateidf(Struts2Utils.getCurrentUser().getIdf());
			user.setIndexCssf(0);
			user.setAddrf("");
			user.setEmailf("");
			user.setMobilePhonef("");
			user.setHomePhonef("");
			user.setOfficePhonef("");
			user.setStatusf(0);
			user.setUserType("3");
			
			
			String userName=uorv.getIdbegin()+uorv.getIdend()+i;
			user.setUserNamef(userName);
			user.setTrueNamef(userName);
			if("yxhxt".equals(uorv.getPwd())){
				user.setUserPwdf(userName);
			}else{
				user.setUserPwdf("8888");
			}
			users.add(user);
		}
		return ((UserService)this.getBaseService()).doInsertUsersb(users,uorv.getRoles(),getQueryMap().get("deptId").toString());
	}
	
	public List<BaseVo> Read(String filePath){
		jxl.Workbook rwb = null;
		List<BaseVo> list=new ArrayList<BaseVo>();
		try {
			// 构建Workbook对象, 只读Workbook对象
			// 直接从本地文件创建Workbook
			// 从输入流创建Workbook
			InputStream is = new FileInputStream(filePath);
			rwb = Workbook.getWorkbook(is);
			Sheet rs = (Sheet) rwb.getSheet(0);
			int reRows = rs.getRows();
			for(int i=1;i<reRows;i++){
				UserVo user=new UserVo();
				Cell userNamef = ((jxl.Sheet) rs).getCell(0, i);
				String userNamefVal = userNamef.getContents();
				
				Cell trueNamef = ((jxl.Sheet) rs).getCell(1, i);
				String trueNamefVal = trueNamef.getContents();
				
				Cell userPwdf = ((jxl.Sheet) rs).getCell(2, i);
				String userPwdfVal = StringUtil.nullOrEmptyToValue(userPwdf.getContents(),"8888");
				
				user.setUserNamef(userNamefVal);
				user.setTrueNamef(trueNamefVal);
				user.setUserPwdf(userPwdfVal);
				
				user.setCreateidf(Struts2Utils.getCurrentUser().getIdf());
				user.setIndexCssf(0);
				user.setAddrf("");
				user.setEmailf("");
				user.setMobilePhonef("");
				user.setHomePhonef("");
				user.setOfficePhonef("");
				user.setStatusf(0);
				user.setUserType("3");
				list.add(user);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			rwb.close();
		}
		return list;
	}
	public String toDownloadmb() throws Exception {
		String path=SysConfUtil.getConfValue("uploadPath")+"\\abc.xls";
		try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            Struts2Utils.getResponse().reset();
            // 设置response的Header
            Struts2Utils.getResponse().addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            Struts2Utils.getResponse().addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(Struts2Utils.getResponse().getOutputStream());
            Struts2Utils.getResponse().setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
		return null;
	}
	//导出批量修改状态
	public String toExportInsertStatus()throws Exception {
		Struts2Utils.getResponse().reset();
		Struts2Utils.getResponse().setContentType("application/vnd.ms-excel");
		Struts2Utils.getResponse().setHeader("Content-disposition", "attachment; filename=InsertError.xls; charset=GBK");
	    OutputStream outputStream=Struts2Utils.getResponse().getOutputStream();
	    List dataList = (List)Struts2Utils.getSession().getAttribute("failList");
	    Struts2Utils.getSession().removeAttribute("failList");
	    String title = "新增用户失败数据表";
		try
		{	
			WritableWorkbook wb = Workbook.createWorkbook(outputStream);
			WritableSheet sheet = wb.createSheet("InsertError", 0);
			sheet.setColumnView(0, 15);
			sheet.setColumnView(1, 70);
			sheet.setColumnView(2, 30);
			sheet.setRowView(0, 25);
			WritableFont headFont = new WritableFont(WritableFont.ARIAL, 18);
			WritableCellFormat wcf_head = new WritableCellFormat(headFont);
			wcf_head.setBorder(Border.ALL, BorderLineStyle.THIN);
			wcf_head.setAlignment(Alignment.CENTRE);
			WritableFont titleFont = new WritableFont(WritableFont.ARIAL, 12);
			WritableCellFormat wcf_title = new WritableCellFormat(titleFont);
			wcf_title.setBorder(Border.ALL, BorderLineStyle.THIN);
			wcf_title.setAlignment(Alignment.CENTRE);
			
			WritableCellFormat wcf_title2 = new WritableCellFormat(titleFont);
			wcf_title2.setBorder(Border.ALL, BorderLineStyle.THIN);
			wcf_title2.setAlignment(Alignment.LEFT);
			sheet.mergeCells(0, 0, 2, 0);
			
			sheet.addCell(new Label(0, 0,  title, wcf_head));

			sheet.addCell(new Label(0, 1, "用户姓名", wcf_title));
			sheet.addCell(new Label(1, 1, "登录账号", wcf_title));
			sheet.addCell(new Label(2, 1, "密码", wcf_title));
			int i = 0;
			for (i = 2; dataList != null && i - 2 < dataList.size(); i++)
			{
				UserVo user = (UserVo)dataList.get(i - 2);
				sheet.addCell(new Label(0, i, user.getTrueNamef(), wcf_title));
				sheet.addCell(new Label(1, i, user.getUserNamef(), wcf_title));
				sheet.addCell(new Label(2, i, user.getUserPwdf(), wcf_title));
			}
			wb.write();
			wb.close();
		}
		catch (Exception e)
		{
			throw new Exception(e);
		}
	    return null;
	}

	public UserOrRoleVo getUorv() {
		return uorv;
	}

	public void setUorv(UserOrRoleVo uorv) {
		this.uorv = uorv;
	}
}
